package DataStructure;

import java.util.Arrays;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-11-08
 * Time: 10:53
 */
public class MyArrayList {

    private int[] elem;
    private int usedSize;
    public final static int DEFAULT_CAPACITY = 10;

    public MyArrayList() {
        this.elem = new int[DEFAULT_CAPACITY];
        this.usedSize = 0;
    }
    public MyArrayList(int capacity) {
        this.elem = new int[capacity];
        this.usedSize = 0;
    }
    private boolean isFull(int minCapacity){
        return (minCapacity - this.elem.length) > 0;
    }
    private void grow(int minCapacity) {
        int oldCapacity = this.elem.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        this.elem = Arrays.copyOf(this.elem, newCapacity);
    }
    private void checkIndex(int pos) {
        if (pos < 0 || pos >= this.usedSize)
            throw new RuntimeException("pos不合法: pos=" + pos);
    }
    public int getLength() {
        return this.usedSize;
    }
    public void add(int data) {
        if (this.isFull(usedSize+1))
            grow(usedSize+1);
        this.elem[this.usedSize] = data;
        this.usedSize++;
    }
    public void add(int pos, int data) {
        checkIndex(pos);
        if (this.isFull(usedSize+1))
            grow(usedSize+1);
        for (int i = this.usedSize; i > pos; i--) {
            this.elem[i] = this.elem[i-1];
        }
        this.elem[pos] = data;
    }
    public boolean contains(int toFind) {
        for (int i =0; i < usedSize; i++) {
            if (this.elem[i] == toFind) return true;
        }
        return false;
    }
    public int get(int pos) {
        checkIndex(pos);
        return this.elem[pos];
    }

    public void set(int pos, int data) {
        checkIndex(pos);
        this.elem[pos] = data;
    }

    public int indexToFind(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (this.elem[i] == toFind) return i;
        }
        return -1;
    }

    public boolean isEmpty(){
        return this.usedSize == 0;
    }

    public void remove(int toRemove) {
        if (!contains(toRemove)) throw new RuntimeException("toRemove不存在");
        for (int i = indexToFind(toRemove); i < usedSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.elem[usedSize-1] = 0;
        this.usedSize--;
    }

    public void clear() {
        for (int i = 0; i < usedSize; i++) {
            this.elem[i] = 0;
        }
        this.usedSize = 0;
    }
}
